const WebSocket = require('ws');
const CONFIG = require(`${process.root}/config`);
const url = CONFIG.bot.ws;
const ws = getWs(url);

module.exports = {
  self: ws,
  send(action, params) {
    ws.send(JSON.stringify({ action, params }))
  },
  onMessage(callback) {
    ws.on('message', data => {
      try {
        callback(JSON.parse(data))
      } catch (e) {
        console.error(e)
      }
    })
  }
}

function getWs(url) {
  let temp = new WebSocket(url);
  temp.on('error', (e) => {
    if (e) {
      console.log(`ws error: ${temp._url}`);
      temp.close();
      temp = undefined;
    }
  })
  // temp.on('open', (e) => {
  //   console.log(e);
  // })
  return temp;
}